﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using qna.Business;
using qna.Services;
using System.Text.RegularExpressions;
using System.IO;

namespace qna.Controls
{
    public partial class QuestionControl : System.Web.UI.UserControl
    {
        public Question Question { get; set; }
        public string txtToSearch { get; set; }


        protected void Page_Load(object sender, EventArgs e)
        {
            //initiate answer service
            QuestionService qsc = new QuestionService();
            AnswerService asc = new AnswerService();
            int uID = Convert.ToInt32(Parent.Page.User.Identity.Name);

            if (Question == null)
            {
                title.InnerText = "Question not found";
            }
            else
            {
                title.InnerText = Question.Title;
                content.InnerText = Question.Content;
                if (txtToSearch != null)
                {
                    if (Question.Content.Contains(txtToSearch) == true)
                    {
                        string NewContent = content.InnerHtml;
                        NewContent = Regex.Replace(NewContent, txtToSearch, "<b>" + txtToSearch + "</b>", RegexOptions.IgnoreCase);
                        content.InnerHtml = NewContent;
                    }
                }
                else
                {
                    content.InnerHtml = ParseContent(Question.Content);
                }
                date.InnerText = Question.DateTimeUpdated.ToString();
                postedBy.Text = Question.UserName;
                rating.Text = qsc.GetQuestionRating(Question.Id).ToString();

                if (Question == null)
                {
                    title.InnerText = "Question not found";
                }
                else
                {
                    title.InnerText = Question.Title;
                    content.InnerText = Question.Content;
                    if (txtToSearch != null)
                    {
                        if (Question.Content.Contains(txtToSearch) == true)
                        {
                            string NewContent = content.InnerHtml;
                            NewContent = Regex.Replace(NewContent, txtToSearch, "<b>" + txtToSearch + "</b>", RegexOptions.IgnoreCase);
                            content.InnerHtml = NewContent;
                        }
                    }
                    else
                    {
                        content.InnerHtml = ParseContent(Question.Content);
                    }
                    date.InnerText = Question.DateTimeUpdated.ToString();
                    postedBy.Text = Question.UserName;
                    rating.Text = qsc.GetQuestionRating(Question.Id).ToString();
                    int total = TotalAnswers(Question.Id);
                    answerLink.Text = "Answers (" + total + ")";
                    answerLink.NavigateUrl = "~/pages/AnswerQnA.aspx?" + "view=" + Question.Id;
					//editBtn.PostBackUrl = "~/pages/EditQuestion.aspx?id=" + Question.Id;
					editLink.NavigateUrl = "~/pages/EditQuestion.aspx?id=" + Question.Id;
                    questionId.Value = Question.Id.ToString();
					if (Question.UserId != Convert.ToInt32(Parent.Page.User.Identity.Name))
					{
						editLink.Visible = false;
					}

                    //set rating.
                    bool userRated = qsc.CheckIfUserRated(Question.Id, uID);

                    if (userRated == true)
                    {
                        imgRating.ImageUrl = "../images/rating_liked.jpg";
                        imgRating.Attributes["onmouseover"] = "this.src='../images/images.jpg'";
                        imgRating.Attributes["onmouseout"] = "this.src='../images/rating_liked.jpg'";
                    }

                    if (Session["userType"] != null && (char)Session["userType"] != User.LECTURER_TYPE)
                    {
                        deleteBtn.Visible = false;
                    }
                }
            }
        }

        private int TotalAnswers(int id)
        {
            AnswerService asc = new AnswerService();
            int count = 0;
            IList<Business.Answer> AnsList = asc.GetByQID(id);
            count = AnsList.Count;
            return count;
        }

        protected void imgRating_Click(object sender, ImageClickEventArgs e)
        {
            QuestionService qsc = new QuestionService();
            int qID = Question.Id;
            int uID = Convert.ToInt32(Parent.Page.User.Identity.Name);
            
            qsc.SetQuestionRating(qID, uID);
            rating.Text = qsc.GetQuestionRating(Question.Id).ToString();

            if (qsc.CheckIfUserRated(qID, uID))
            {
                imgRating.ImageUrl = "../images/rating_liked.jpg";
                imgRating.Attributes["onmouseout"] = "this.src='../images/images.jpg'";
                imgRating.Attributes["onmouseover"] = "this.src='../images/rating_liked.jpg'";

            }
            else
            {
                imgRating.ImageUrl = "../images/images.jpg";
                imgRating.Attributes["onmouseover"] = "this.src='../images/rating_liked.jpg'";
                imgRating.Attributes["onmouseout"] = "this.src='../images/images.jpg'";
                rating.Text = qsc.GetQuestionRating(qID).ToString();
            }


        }

        protected void subscribeBtn_Click(object sender, ImageClickEventArgs e)
        {
            subscription s = new subscription();
            try
            {
                s.Id = Convert.ToInt32(Parent.Page.User.Identity.Name);
                s.QnId = Convert.ToInt32(Question.Id);
                s.Insert(false);
            }
            catch
            {
                s.Delete(Question.Id, s.Id);
            }
        }

         private string ParseContent(string html)
        {
            if (!html.Contains("http://") && !html.Contains("https://"))
            {
                return html;
            }

            string result = "";
            using (StringReader reader = new StringReader(html))
            {
                string line, newLine, newWord = "";
                while ((line = reader.ReadLine()) != null)
                {
                    newLine = "";
                    string[] words = line.Split(new char[1] { ' ' });
                    foreach (var word in words)
                    {
                        if (RgURL.IsMatch(word))
                        {
                            //youtube
                            if (word.StartsWith("http://youtu.be/"))
                            {
                                string id = Regex.Match(word, "http://youtu.be/([^\\s]+)").Groups[1].Value;
                                newWord = "<object width=\"390\" height=\"640\">"
                                    + "<param name=\"movie\" value=\"http://www.youtube.com/v/" + id + "?version=3&amp;hl=en_GB\"></param>"
                                    + "<param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param>"
                                    + "<embed src=\"http://www.youtube.com/v/" + id + "?version=3&amp;hl=en_GB\" type=\"application/x-shockwave-flash\" width=\"640\" height=\"390\" allowscriptaccess=\"always\" allowfullscreen=\"true\" wmode=\"opaque\"></embed>"
                                    + "</object>";
                            }
                            else if (Regex.IsMatch(word, ".(png|jpg|gif)"))
                                //images
                                newWord = "<img src=\"" + word + "\" />";
                            else
                                //rest of the links
                                newWord = "<a href=\"" + word + "\" target='_blank'>" + word + "</a>";
                        }
                        else
                            newWord = word;
                        newLine += newWord + " ";
                    }
                    result += "<p>" + (newLine == " " ? "&nbsp;" : newLine) + "</p>";
                }
            }
            return result;
        }

        public Regex RgURL = new Regex(@"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])", RegexOptions.IgnoreCase);
    }
}